package com.hks360.car_treasure.fragment;

import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.hks360.car_treasure.R;
import com.hks360.car_treasure.common.BaiduMapConfig;
import com.hks360.car_treasure.dialog.DateDialog;
import com.hks360.car_treasure.manager.CommonDataManager;
import com.hks360.car_treasure.util.DateUtils;
import com.hks360.car_treasure.listener.TrakeLocationListener;
import com.hks360.library.util.CommonUtil;
import com.hks360.library.util.UIUtil;
import com.hks360.library.widget.CheckImageView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 行程Fragment
 */
public class StrokeFragment extends BaseFragment {
    List<LatLng> points;
    private TextureMapView mStrokeMv;
    private TrakeLocationListener mLocationListener;
    private BaiduMap mBaiduMap;
    private boolean isFirstLoc = true;
    private LocationClient mLocClient;
    private CheckImageView mMapPlusIv;
    private CheckImageView mMapMinusIv;
    private float mZoomLevel = BaiduMapConfig.ZOOM_BIG;
    private LinearLayout content;
    private EditText et_date_start;
    private EditText et_date_end;
    private TextView tv_confirm;
    private TextView tv_cancel;
    private AlertDialog adialog;

    private int startTime = 0;
    private int endTime = 0;

    private String year;
    private String month;
    private String day;
    private String hour;
    private String minute;
    private BDLocation location;

    private int count;
    private int i;
    private LatLng ll;
    private LatLng L1;
    private LatLng L2;
    private double middleX;
    private double middleY;
    private double startX;
    private double startY;
    private double endX;
    private double endY;
    private double dx;
    private double dy;
    private CountDownTimer cdt;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            count = points.size();
            L1 = new LatLng(middleX, middleY);
            middleX = middleX + dx;
            middleY = middleY + dy;
            L2 = new LatLng(middleX, middleY);
            drawLine(L1, L2);
            locationMe(middleX, middleY);
        }
    };
    private long interval = 100;
    private double speed = 100;


    public void setupView() {
        mStrokeMv = UIUtil.findViewById(mRootView, R.id.stroke_mv);
        mMapPlusIv = UIUtil.findViewById(mRootView, R.id.stroke_mapplus_iv);
        mMapMinusIv = UIUtil.findViewById(mRootView, R.id.stroke_mapminus_iv);
        et_date_start = UIUtil.findViewById(content, R.id.et_start);
        et_date_end = UIUtil.findViewById(content, R.id.et_overtime);
        tv_confirm = UIUtil.findViewById(content, R.id.tv_dialog_confirm);
        tv_cancel = UIUtil.findViewById(content, R.id.tv_dialog_cancel);
        ll = new LatLng(0, 0);
        initPoints();

    }

    @Override
    public void initData() {
        mStrokeMv.showZoomControls(false);
        mBaiduMap = mStrokeMv.getMap();
        location = new BDLocation();
        mBaiduMap.setMyLocationEnabled(true);
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(5)
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(BaiduMapConfig.MAP_ROTATE_DEFAULT).latitude(30.33268)
                .longitude(120.1322).build();
        mBaiduMap.setMyLocationData(locData);
        initZoom();
        showDatePickDialog();
    }

    private void initZoom() {
        LatLng ll = new LatLng(30.33268, 120.1322);
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(ll).zoom(mZoomLevel);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }

    private void showDatePickDialog() {
        AlertDialog.Builder pdBuidler = new AlertDialog.Builder(getContext());
        adialog = pdBuidler.setView(content).create();
        adialog.show();
    }

    @Override
    public void addListener() {
        mMapPlusIv.setOnClickListener(this);
        mMapMinusIv.setOnClickListener(this);
        et_date_start.setOnClickListener(this);
        et_date_end.setOnClickListener(this);
        tv_confirm.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
    }

    @Override
    public void initView() {
        initTitleBar(R.string.title_stroke);
        setupView();
        initData();
        addListener();
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        getActivity().getWindow().setFormat(PixelFormat.TRANSLUCENT);
        content = (LinearLayout) getLayoutInflater(savedInstanceState).inflate(R.layout.dialog_date_choose, null);
        mRootView = inflater.inflate(R.layout.fragment_stroke, null);
        initView();
        return mRootView;
    }

    @Override
    public void onPause() {
        mStrokeMv.onPause();
        if (cdt != null) {
            cdt.cancel();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        mStrokeMv.onResume();
        super.onResume();
    }

    @Override
    public void onDestroyView() {
//        if(mBaiduMap != null){
//            mBaiduMap.clear();
//        }
        mStrokeMv.onDestroy();
        super.onDestroyView();
    }

    @Override
    public void viewClick(View v) {
        switch (v.getId()) {
            case R.id.stroke_mapplus_iv: //放大地图
                map_zoom_plus();
                break;
            case R.id.stroke_mapminus_iv:    //缩小地图
                map_zoom_minus();
                break;
            case R.id.et_start:
                queryTrack(et_date_start);
                break;
            case R.id.et_overtime:
                //// TODO: 2016/4/1   判断开始的时间应该大于结束的时间
                queryTrack(et_date_end);
                break;
            case R.id.tv_dialog_confirm:
                String date1 = et_date_start.getText().toString().trim();
                String date2 = et_date_end.getText().toString().trim();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    long time1 = format.parse(date1).getTime();
                    long time2 = format.parse(date2).getTime();
                    if (time2 < time1) {
                        CommonUtil.showToast(getContext(), "结束时间应该大于起始时间");
                        return;
                    }
                } catch (Exception e) {

                }
                adialog.dismiss();
                animationPlay();
                break;
            case R.id.tv_dialog_cancel:
                adialog.dismiss();
                break;
        }
    }

    private void animationPlay() {
        i = 0;
        initDataPath();
        cdt = new CountDownTimer(10000, interval) {
            @Override
            public void onTick(long l) {
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onFinish() {
                i++;
                if (i < count - 1) {
                    L1 = new LatLng(middleX, middleY);
                    initDataPath();
                    L2 = new LatLng(startX, startY);
                    drawLine(L1, L2);
                    cdt.start();
                }
            }
        }.start();

    }

    //初始化动画放映的数据
    private void initDataPath() {
        startX = points.get(i).latitude;
        startY = points.get(i).longitude;
        endX = points.get(i + 1).latitude;
        endY = points.get(i + 1).longitude;
        middleX = startX;
        middleY = startY;
        count = points.size();
        dx = (endX - startX) / (speed - 1);
        dy = (endY - startY) / (speed - 1);
    }

    //获取当前位置根据经纬度
    private void locationMe(double x, double y) {
        LatLng p = new LatLng(x, y);
        mBaiduMap.setMyLocationEnabled(true);
        mStrokeMv.showZoomControls(true);
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(p).zoom(mZoomLevel);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(5)
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(BaiduMapConfig.MAP_ROTATE_DEFAULT).latitude(p.latitude)
                .longitude(p.longitude).build();
        mBaiduMap.setMyLocationData(locData);
    }

    //两点划线
    private void drawLine(LatLng l1, LatLng l2) {
        // 构造折线点坐标
        List<LatLng> points = new ArrayList<LatLng>();
        points.add(l1);
        points.add(l2);
        //构建分段颜色索引数组
        List<Integer> colors = new ArrayList<Integer>();
        colors.add(Integer.valueOf(Color.BLUE));
        OverlayOptions ooPolyline = new PolylineOptions().width(10)
                .colorsValues(colors).points(points);
//        添加在地图中
        Polyline mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);
        //定义文字所显示的坐标点
    }

    //初始化路径  从网络获取
    private void initPoints() {

        // 构造折线点坐标
        points = new ArrayList<LatLng>();
        points.add(new LatLng(30.33268, 120.1322));
        points.add(new LatLng(30.32913, 120.1331));
        points.add(new LatLng(30.32821, 120.1304));
        points.add(new LatLng(30.33143, 120.1284));


//        LatLng llText = new LatLng(30.33170, 120.1291);
//        //构建文字Option对象，用于在地图上添加文字
//        OverlayOptions textOption = new TextOptions()
//                .bgColor(0xAAFFFF00)
//                .fontSize(24)
//                .fontColor(0xFFFF00FF)
//                .text("百度地图SDK")
//                .rotate(-30)
//                .position(llText);
//        //在地图上添加该文字对象并显示
//        mBaiduMap.addOverlay(textOption);
    }

    //放大地图
    private void map_zoom_plus() {
        mZoomLevel++;
        showZoom();
    }

    //缩小地图
    private void map_zoom_minus() {
        mZoomLevel--;
        showZoom();
    }

    private void showZoom() {
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.zoom(mZoomLevel);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        zoom_image_status();
    }

    private void zoom_image_status() {
        if (mZoomLevel == mBaiduMap.getMinZoomLevel()) {
            mMapMinusIv.setEnabled(false);
        } else if (mZoomLevel == mBaiduMap.getMaxZoomLevel()) {
            mMapPlusIv.setEnabled(false);
        } else {
            mMapMinusIv.setEnabled(true);
            mMapPlusIv.setEnabled(true);
        }
    }

    /**
     * 轨迹查询(先选择日期，再根据是否纠偏，发送请求)
     */
    private void queryTrack(final EditText tvDatetime) {
        year = new String();
        month = new String();
        day = new String();
        hour = new String();
        minute = new String();
        // 选择日期
        String[] date = new String[5];
        DisplayMetrics dm = new DisplayMetrics();
        this.getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int height = dm.heightPixels;

        if (year.isEmpty() && month.isEmpty() && day.isEmpty()) {
            String curDate = DateUtils.getCurrentDate();
            date = DateUtils.getYMDArray(curDate, "-");
        }

        if (date != null) {
            year = date[0];
            month = date[1];
            day = date[2];
            hour = date[3];
            minute = date[4];
        }

        DateDialog dateDiolog = new DateDialog(this.getActivity(), new DateDialog.PriorityListener() {
            @Override
            public void refreshPriorityUI(String sltYear, String sltMonth, String sltDay, String slthour, String sltmin, DateDialog.CallBack back) {
                year = sltYear;
                month = sltMonth;
                day = sltDay;
                hour = slthour;
                minute = sltmin;
                back.execute();
            }
        }, new DateDialog.CallBack() {

            public void execute() {
                tvDatetime.setText(year + "-" + month + "-" + day + " " + hour + ":" + minute);
            }
        }, year, month, day, hour, minute, width, height, "选择日期", 1);
        Window window = dateDiolog.getWindow();
        window.setGravity(Gravity.CENTER); // 此处可以设置dialog显示的位置
        dateDiolog.setCancelable(true);
        dateDiolog.show();
    }
}
